/*
 * @Author: yangzonglong
 * @Date: 2020-08-28 10:40:00
 * @version: v1.0.0
 * @Descripttion: 排序
 * @LastEditors: yangzonglong
 * @LastEditTime: 2020-09-07 17:31:33
 * @Auditor: 
 */

const getMax = (arr: any[], sortkey: string) => Math.max.apply(null, arr.map(item => item[sortkey] || 0));
const getMin = (arr: any[], sortkey: string) => Math.min.apply(null, arr.map(item => item[sortkey] || 9999999));

export default function sort(arr: any[], sortkey: string, sortType?: 'DESC' | 'ASC') {

  const isDESC = sortType === 'DESC';

  let order: number = isDESC ? getMin(arr, sortkey) : getMax(arr, sortkey);
  let handleArr = arr.map(item => ({ ...item, _index: isDESC ? --order : ++order }));

  return handleArr.sort((obj1, obj2) => {

    let obj1SortOrder = obj1[sortkey];
    let obj2SortOrder = obj2[sortkey];

    if (typeof obj1SortOrder === 'undefined') obj1SortOrder = obj1._index;
    if (typeof obj2SortOrder === 'undefined') obj2SortOrder = obj2._index;

    if (obj2SortOrder > obj1SortOrder) return isDESC ? 1 : -1;

    return isDESC ? -1 : 1
  })
}